package JUC;

/**
 * @author 豆包LU
 * @date 2023/5/22 22:26
 */
public class DataSharingExample {
    public static void main(String[] args) {
        // 创建共享数据对象
        Data sharedData = new Data();

        // 创建父线程，并传递共享数据对象
        ParentThread parentThread = new ParentThread(sharedData);

        // 创建子线程，并传递共享数据对象
        ChildThread childThread = new ChildThread(sharedData);

        // 启动父线程和子线程
        parentThread.start();
        childThread.start();
    }
}

// 共享数据对象
class Data {
    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}

// 父线程
class ParentThread extends Thread {
    private Data sharedData;

    public ParentThread(Data sharedData) {
        this.sharedData = sharedData;
    }

    @Override
    public void run() {
        // 设置共享数据的值
        sharedData.setValue(10);
        System.out.println("父线程设置共享数据为: " + sharedData.getValue());
    }
}

// 子线程
class ChildThread extends Thread {
    private Data sharedData;

    public ChildThread(Data sharedData) {
        this.sharedData = sharedData;
    }

    @Override
    public void run() {
        // 获取共享数据的值
        int value = sharedData.getValue();
        System.out.println("子线程读取共享数据的值为: " + value);
    }
}

